package io.renren.controller;

import io.renren.common.utils.Result;
import io.renren.dto.FileResultVo;
import io.renren.service.UploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("order/shoporder/upload")
@Tag(name = "上传文件") // Changed from @Api
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @Operation(summary = "图片上传") // Changed from @ApiOperation
    @RequestMapping(value = "/image", method = RequestMethod.POST)
    @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "要上传的图片文件") // Adding RequestBody for multipart file
    public Result<FileResultVo> image(@Parameter(description = "要上传的图片文件", required = true) MultipartFile multipart, // Changed from @ApiImplicitParam
                                      @Parameter(name = "model", description = "模块 用户user,商品product,微信wechat,news文章", required = true) @RequestParam(value = "model") String model, // Changed from @ApiImplicitParam
                                      @Parameter(name = "pid", description = "分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列 ", required = true) @RequestParam(value = "pid") Integer pid) throws IOException {
        return new Result().ok(uploadService.imageUpload(multipart, model, pid));
    }

    @Operation(summary = "文件上传") // Changed from @ApiOperation
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "要上传的文件") // Adding RequestBody for multipart file
    public Result<FileResultVo> file(@Parameter(description = "要上传的文件", required = true) MultipartFile multipart, // Changed from @ApiImplicitParam
                                     @Parameter(name = "model", description = "模块 用户user,商品product,微信wechat,news文章", required = true) @RequestParam(value = "model") String model, // Changed from @ApiImplicitParam
                                     @Parameter(name = "pid", description = "分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列 ", required = true) @RequestParam(value = "pid") Integer pid) throws IOException {
        return new Result().ok(uploadService.fileUpload(multipart, model, pid));
    }

    @PostMapping("/image/base64")
    @Operation(summary = "上传图片并返回base64") // Changed from @ApiOperation
    public Map<String, String> uploadImageToBase64(@Parameter(description = "要上传的图片文件", required = true) @RequestParam("file") MultipartFile file) { // Changed from @ApiImplicitParam
        Map<String, String> result = new HashMap<>();

        if (file.isEmpty()) {
            result.put("error", "文件为空");
            return result;
        }

        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            result.put("error", "只支持图片文件");
            return result;
        }

        try (InputStream inputStream = file.getInputStream()) {
            // Read file content into byte array
            byte[] fileContent = IOUtils.toByteArray(inputStream);

            // Convert to base64
            String base64String = Base64.getEncoder().encodeToString(fileContent);
            String base64Image = "data:" + contentType + ";base64," + base64String;

            result.put("base64", base64Image);
            result.put("originalFileName", file.getOriginalFilename());

            // Ensure data in memory is cleaned up
            fileContent = null;
            System.gc(); // This is a hint to the JVM, not a guarantee of immediate garbage collection

            return result;
        } catch (IOException e) {
            log.error("图片转换base64失败", e);
            result.put("error", "图片处理失败");
            return result;
        }
    }
}